package com.mingzhi.forum.controller;

import com.mingzhi.forum.common.AppResult;
import com.mingzhi.forum.common.ResultCode;
import com.mingzhi.forum.config.AppConfig;
import com.mingzhi.forum.model.User;
import com.mingzhi.forum.service.IUserService;
import com.mingzhi.forum.utils.MD5Util;
import com.mingzhi.forum.utils.StringUtil;
import com.mingzhi.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

//API描述
@Tag(name = "用户接口API", description = "用户进行注册")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 注册
     *
     * @param username       用户名
     * @param nickname       昵称
     * @param password       密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @Operation(summary = "用户注册")
    @PostMapping(value = "/register")
    public AppResult register(@Parameter(name = "username", description = "用户名") @RequestParam("username") @NonNull String username,
                              @Parameter(name = "nickname", description = "用户昵称") @RequestParam("nickname") @NonNull String nickname,
                              @Parameter(name = "password", description = "用户密码") @RequestParam("password") @NonNull String password,
                              @Parameter(name = "passwordRepeat", description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //先进行校验
        //这个一个传统的校验方式，也可以使用注解进行实现
        /*if (StringUtil.isEmpty(username)
                || StringUtil.isEmpty(nickname)
                || StringUtil.isEmpty(password)
                || StringUtil.isEmpty(passwordRepeat)) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/

        //校验 密码和确认密码 是否一致
        if (!password.equals(passwordRepeat)) {
            //打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //直接返回
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //创建一个用户
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐
        String salt = UUIDUtil.UUID_32();
        //MD5加密
        String encryptPassword = MD5Util.md5Salt(password, salt);
        user.setPassword(encryptPassword);
        //设置盐
        user.setSalt(salt);

        //调用service
        userService.createNormalUser(user);
        return AppResult.success();
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @Parameter(description = "用户名") @RequestParam("username") @NonNull String username,
                           @Parameter(description = "密码") @RequestParam("password") @NonNull String password) {
        User user = userService.login(username, password);
        //设置session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        log.info("登录成功：username = " + username);
        //登录成功，返回响应
        return AppResult.success();
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @Parameter(description = "用户Id") @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        //根据参数中的id是否为空来决定返回哪个用户
        if (id == null) {
            //返回登录用户，从session中获取
            //不创建新的session
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            //根据id查询用户的信息
            user = userService.selectById(id);
        }
        //判断用户对象是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @Operation(summary = "用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            //打印日志
            log.info("退出成功");
            //注销session
            session.invalidate();
        }
        //退出成功响应
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人基本信息
     *
     * @param username 用户名
     * @param nickname 昵称
     * @param gender   性别
     * @param email    邮箱
     * @param phoneNum 电话号
     * @param remark   个人简介
     * @return
     */
    @Operation(summary = "修改个人基本信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @Parameter(description = "用户名") @RequestParam(value = "username", required = false) String username,
                                @Parameter(description = "昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @Parameter(description = "性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @Parameter(description = "邮箱") @RequestParam(value = "email", required = false) String email,
                                @Parameter(description = "电话号") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @Parameter(description = "个人简介") @RequestParam(value = "remark", required = false) String remark) {
        //非空校验
        if (StringUtil.isEmpty(username)
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark)
                && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }
        //从session中获取id
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);

        //封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        //调用service
        userService.modifyInfo(updateUser);
        //查询新的用户信息
        user = userService.selectById(user.getId());
        // 6. session
        request.getSession(false).setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    @Operation(summary = "修改用户密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @Parameter(description = "用户id") @RequestParam("id") @NonNull Long id,
                                    @Parameter(description = "老密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @Parameter(description = "新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //判断新密码是否与确认密码相同
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //根据session获取用户对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service层
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        if (session != null){
            session.invalidate();
        }
        return AppResult.success();
    }
}
